package com.my.bbs.service.impl;

import com.my.bbs.common.Constants;
import com.my.bbs.common.ServiceResultEnum;
import com.my.bbs.service.MyEmailService;
import com.my.bbs.util.Result;
import com.my.bbs.util.ResultGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author 86187
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class MyEmailServiceImpl implements MyEmailService {

    @Autowired
    JavaMailSenderImpl mailSender;
    @Override
    public Result sendMail(String loginName, HttpSession session) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        StringBuilder code = new StringBuilder();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setSubject("Your Verification code");
            Random random = new Random();
            for (int i = 0; i < 4; i++) {
                code.append(random.nextInt(10));
            }
            String text = "Your Verification code is:" + "<h4 style='color: red'>" + code + "</h4>" + "Please don't divulge";
            helper.setText(text);
            helper.setTo(loginName);
            helper.setFrom("2367792309@qq.com");
            helper.setSentDate(new Date());
            log.info("开始发送邮件， 当前时间：" + dateFormat.format(new Date()));
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            return ResultGenerator.genFailResult(ServiceResultEnum.SEND_FAILURE.getResult());
        }
        log.info("邮件发送成功！当前时间：" + dateFormat.format(new Date()));
        session.setAttribute(Constants.EMAIL_CODE, code);
        return ResultGenerator.genSuccessResult();
    }
}
